package cn.xiaoxiang.basic.util;

import cn.xiaoxiang.basic.jwt.*;
import cn.xiaoxiang.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;


import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.security.PublicKey;

//登录上下文，把登录的相关信息放到这里面，方便调用
// 问题1：
/**
* @Description: 登录上下文工具类，获取当前登录人信息
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/7/3 11:20
*/


    @Slf4j
    public class LoginContext {


        public static Logininfo getLogininfo(HttpServletRequest request) throws Exception {
            String token = request.getHeader("token");
            // 如果token存在 去reids中查询
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(JwtRasHolder.INSTANCE.getJwtRsaPubData()).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            if (null == payload.getUserInfo()){
                log.info("从jwt中获取用户信息为null");
            }
            return payload.getUserInfo().getLogininfo();
        }

        public static UserInfo getUserInfo(){
            UserInfo userInfo = ThreadLocalUtil.getUserInfo();
            UserInfo result = new UserInfo();
            result.setLogininfo(userInfo.getLogininfo());
            result.setShop(userInfo.getShop());
            ThreadLocalUtil.remove();
            return result;
        }

    }
